package com.example.lenovo.downloaddemo.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;

import com.bumptech.glide.Glide;
import com.example.lenovo.downloaddemo.activity.MoreActivity;
import com.example.lenovo.downloaddemo.adapter.CategoryAdapter;
import com.example.lenovo.downloaddemo.bean.CategoryBean;
import com.example.lenovo.downloaddemo.bean.Customer;
import com.example.lenovo.downloaddemo.R;
import com.example.lenovo.downloaddemo.http.AppConfig;
import com.example.lenovo.downloaddemo.http.datasource.MDataSource;
import com.example.lenovo.downloaddemo.http.okhttp.utils.AppContext;
import com.example.lenovo.downloaddemo.http.okhttp.utils.Collintion;
import com.example.lenovo.downloaddemo.http.okhttp.utils.CommonUtils;
import com.example.lenovo.downloaddemo.http.okhttp.utils.MD5;
import com.example.lenovo.downloaddemo.http.okhttp.utils.ToastUtil;
import com.example.lenovo.downloaddemo.sqlite.LoadListCallBack;
import com.example.lenovo.downloaddemo.util.StatusBarUtil;
import com.example.lenovo.downloaddemo.util.TimeUtil;
import com.example.lenovo.downloaddemo.view.TitleBarView;
import com.google.gson.Gson;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.OkHttpClient;
import okhttp3.Request;


/**
 * 分类页面
 * */
public class CategoryFragment extends Fragment {
    @Bind(R.id.category_titleBar)
    TitleBarView titleBarView;
    @Bind(R.id.category_banner)
    Banner banner;

    @Bind(R.id.category_ListView)
    ListView category_ListView;
    private CategoryAdapter adapter;

    private String allString;

    private   List<CategoryBean.DataBean.CategoryListBean> list;
    public static CategoryFragment instance;
    private View view;
    private Context context;
    final OkHttpClient client = new OkHttpClient();

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                String returnMessage= (String) msg.obj;
                Log.e("msg===",returnMessage.toString());
                Gson gson=new Gson();

                try {
                    CategoryBean bean = gson.fromJson(returnMessage, CategoryBean.class);

                    if (bean.getCode() == 200) {
                        List<CategoryBean.DataBean.BannerBean> data = new ArrayList<>();
                        data = bean.getData().getBanner();
                        List<String> urlList = new ArrayList<>();
                        for (int i = 0; i < data.size(); i++) {

                            //data.add("http://192.168.1.222:2010"+bean.getData().getGoodsList().get(i).getGood_pic());

                            urlList.add(AppConfig.IP + data.get(i).getPic());
                            Log.e("图片地址===", AppConfig.IP + data.get(i).getPic());
                            banner.setImageLoader(new ImageLoader() {
                                @Override
                                public void displayImage(Context context, Object path, ImageView imageView) {
                                    imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                                    Glide.with(context).load((String)path).into(imageView);
                                }
                            });
                        }
//                        banner.setImageLoader(new GlideUtils());




                        banner.setImages(urlList);
                    banner.start();
                        list = new ArrayList<>();
                        list = bean.getData().getCategoryList();
                        adapter = new CategoryAdapter(getActivity(), list);
                        category_ListView.setAdapter(adapter);

                        category_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                Intent intent = new Intent(getActivity(), MoreActivity.class);
                                intent.putExtra("c_id", list.get(i).getC_id());
                                Log.e("cid===", list.get(i).getC_id() + "");
//                            ToastUtil.makeText(getActivity(),"你点击了第"+i+"个");
                                startActivity(intent);
                            }
                        });


                    }
                }catch (Exception e){
                    ToastUtil.makeText(getActivity(),"请求错误");
                }

            }


        }
    };


    public static CategoryFragment getInstance(){
        if(null==instance){
            instance=new CategoryFragment();
        }
        return instance;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context=context;

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == view) {
            view = inflater.inflate(R.layout.fragment_category, container, false);
            ButterKnife.bind(this, view);
            initView();
        } else {
            if (null != view.getParent()) {
                ((ViewGroup) view.getParent()).removeAllViews();
            }

        }
        instance = this;
        return view;
    }

    private void initView() {
        StatusBarUtil.setMargin(context,titleBarView);
        titleBarView.setTitle(AppContext.getInstance().getResources().getString(R.string.fenlei));
        titleBarView.showBackButton(false);
        //设置样式
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        banner.setIndicatorGravity(BannerConfig.CENTER);
        banner.setDelayTime(3000);//设置轮播间隔时间
        initData();



    }

    private void initData() {

//        HashMap<String,String> map=new HashMap<>();


    }

    @Override
    public void onPause() {
        super.onPause();
        banner.stopAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        banner.stopAutoPlay();
    }

    @Override
    public void onResume() {
        super.onResume();
        banner.start();
        if(CommonUtils.isNetOk(AppContext.getInstance())){
            postRequest();
        }else{
            ToastUtil.makeText(AppContext.getInstance(),"Fail!");
        }
    }

    /**
     * 分类
     */
    private void postRequest() {
        /**
         * 建立请求表单，添加上传服务器的参数
         */
        HashMap<String, String> map = new HashMap<>();
        map.put("model", "index");
        map.put("method", "categoryList");

        map.put("time",new TimeUtil().getMoment());
        Collintion collintion=new Collintion();

        allString=collintion.Sort(map)+"ad1af567dc7bfedd5e760fc1f48a59ae";
        String sign= MD5.GetMD5Code(MD5.GetMD5Code(allString));
        Log.e("拼接字符串",allString);
        Log.e("签名===",sign);
        map.put("sign",sign);

        MDataSource<Customer> dataSource = new MDataSource<>(getActivity());
        dataSource.postData(map, new LoadListCallBack() {
            @Override
            public void loadList(List list) {

            }

            @Override
            public void systemError(Request request, String errorInfo, Exception e) {
                Log.e("error", "systemError: " + errorInfo);
                e.printStackTrace();
            }

            @Override
            public void retLoad(String code) {

            }

            @Override
            public void loadString(String string) {
                Log.e("登陆结果", "loadString 登录结果 : " + string);

                Message message=Message.obtain();
                message.what=1;
                message.obj=string;
                mHandler.sendMessage(message);





            }
        });
    }
}
